package com.example.express_user.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
@EnableResourceServer
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {
    /**
     * 当资源请求发送到Resource Server的时候会携带access_token，Resource Server会
     * 根据access_token找到client_id，进而找到该client可以访问的resource_ids。
     * 如果resource_ids包含ResourceServer自己设置ResourceID，这关就过去了，就可以继续进行其他的权限验证
     */
    public static final String RESOURCE_ID = "EXPRESS_USER_1";

    @Autowired
    TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID)//资源id
                .tokenStore(tokenStore)//让资源服务自己验证token
                //.tokenServices(tokenService())//验证令牌的服务
                .stateless(true);//标志，指示在这些资源上只允许基于令牌的身份验证。
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .antMatchers("/user-controller/**").access("#oauth2.hasAnyScope('ROLE_ORDER_ADMIN,ROLE_USER,ROLE_COURIER,ROLE_API')")
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);//session不记录
    }

}
